package com.rpc.core.loadbalance.impl;

import com.rpc.core.holder.rag.RegInfoEnhancer;
import com.rpc.core.loadbalance.LoadBalance;
import com.rpc.core.remoting.Client;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;


//polling
public class PollingLoadBalance implements LoadBalance {


    private AtomicInteger index = new AtomicInteger(0);

    @Override
    public RegInfoEnhancer get(List<RegInfoEnhancer> list) {

        int tryCount = 0;
        for (; ; ) {
            if (tryCount == list.size()) {
                return null;
            }
            int i = index.getAndUpdate((a) -> {
                if (a + 1 >= list.size())
                    return 0;
                return a + 1;
            }) % list.size();
            RegInfoEnhancer enhancer = list.get(i);
            Client client = enhancer.getClient();
            if (client != null) {
                return enhancer;
            } else {
                tryCount++;
            }
        }

    }
}
